#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int dirCount(const char *dirName){
        int total = 0;

        //打开目录
        DIR *dirp = opendir(dirName);
        if(dirp == NULL){
                perror("opendir error");
                return -1;
        }

        //循环读目录,如果是普通目录,count++,如果是目录,继续调用dirCount
        struct dirent *dentp = NULL;
        while ( (dentp = readdir(dirp)) != NULL){ //如果为NULL,代表读到了目录末尾
                //printf("dirname:%s, dtype:%d\n", dentp->d_name, dentp->d_type);
                //打印发现有.和..两个目录,这个是不要统计在内的
                if(dentp->d_type == DT_DIR){ //如果是目录
                        if(strcmp(".", dentp->d_name) || strcmp("..", dentp->d_name)){
                                continue;//如果是.或者..,直接跳过
                        }
                        //注意进程的工作路径
                        //使用dirName拼接下一级目录
                        char newDirName[1024] = {0};
                        sprintf(newDirName,"%s/%s",dirName, dentp->d_name);
                        total += dirCount(newDirName);
                }

                if(dentp->d_type == DT_REG){
                        printf("%s\n", dentp->d_name);
                        total++;
                }
        }

        return total;
}

int main(int argc, char const *argv[])
{
        if(argc != 2){
                printf("./a.out dir name\n");
                return -1;
        }

        dirCount(argv[1]);

        return 0;
}
